#-*- coding:utf-8 -*-
import requests;
from lxml import etree;
import csv;
import time;

def write_csv(item):
	with open('qfang.csv','a',encoding='GBK') as f:
		writer=csv.writer(f);
		try:
			writer.writerow(item);
		except:
			print('写入错误');	

if __name__ == '__main__':
	header={'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'};
	start_url='http://chengdu.qfang.com/newhouse/list/n';
	for i in range(1,20):
		url=start_url+str(i);
		html=requests.get(url,headers=header);
		time.sleep(1);
		selector=etree.HTML(html.text);
		xiaoquList=selector.xpath('//*[@id="newhouse-list"]/li');
		for xiaoqu in xiaoquList:
			name=xiaoqu.xpath('div[1]/p/a/text()')[0];
			bankuai=xiaoqu.xpath('div[1]/div/p[2]/span[2]/text()')[0];
			price=xiaoqu.xpath('div[2]/span[1]/text()')[0];
			item=[name,bankuai,price];
			write_csv(item);
			print('正在抓取%d:%s'%(i,name));